package tk.mybatis.springboot.controller;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.springboot.model.*;
import tk.mybatis.springboot.service.TransactionService;
import tk.mybatis.springboot.util.JsonResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/trans")
public class TransactionController {

    @Autowired
    private TransactionService transactionService;

    //显示存款页面
    @RequestMapping(value = "/showDeposit")
    public String showDeposit(){
        return "bank/deposit";
    }
    //显示取款页面
    @RequestMapping(value = "/showWithdrawals")
    public String showWithdrawals(){
        return "bank/withdrawals";
    }
    //显示转账页面
    @RequestMapping(value = "/showTransfer")
    public String showTransfer(){
        return "bank/transfer";
    }
    //显示交易记录页面
    @RequestMapping(value = "/showAllTrans")
    public String showAllTrans(){
        return "bank/records";
    }

    //存款
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult<Integer> saveMoney(Transaction transaction, HttpSession session) {
        JsonResult<Integer> jsonResult=new JsonResult<Integer>();
        Account account=(Account)session.getAttribute("account");
        try{
            int n=transactionService.saveMoney(transaction,account);
            if (n>0) {
                jsonResult.setState(0);
                jsonResult.setMessage("操作成功");
                jsonResult.setData(n);
            }else{
                jsonResult.setState(1);
                jsonResult.setMessage("操作失败");
            }
        }catch (Exception e){
            return new JsonResult<Integer>(e);
        }
        return jsonResult;
    }

    //查看交易记录
    //根据session找到所有的交易记录，返回trans列表
    @RequestMapping(value = "/getAllTrans")
    @ResponseBody
    public Map<String,Object> getAllTrans(Transaction transaction, HttpServletRequest request) {
        String beginTime=request.getParameter("beginTime");
        String endTime=request.getParameter("endTime");
        //String type=request.getParameter("type");
        Map<String,Object> map=new HashMap();
        Account account=(Account)request.getSession().getAttribute("account");
        List<Transaction> transactions = transactionService.getAllTrans(transaction,account,beginTime,endTime);
        PageInfo<Transaction>  pagelist=new PageInfo<Transaction>(transactions);
        map.put("rows",pagelist.getList());
        map.put("total",pagelist.getTotal());

        return map;
    }
}
